var env = process.argv[2];
var Client = require("ssh2").Client;
var path = require("path");
var fs = require("fs");
var serverConfig = {
  host: "your host",
  port: 22,
  user: "user",
  password: "pwd"
};
var conf = {
  ftpUploadPath: "/www/website/boilerplate"
};

if (!env || !["test", "pre", "prd"].includes(env)) {
  env = "test";
}

if (env) {
  conf.ftpUploadPath += `/${env}`;
}
console.log("目标ftp路径" + conf.ftpUploadPath);

UploadFile(serverConfig);

var fileCount = 0;
function UploadFile(server, localPath, remotePath, then) {
  Connect(server, function(conn) {
    conn.sftp(function(err, sftp) {
      if (err) {
        then(err);
      } else {
        var localPath = path.join(__dirname, "dist");
        walk(
          localPath,
          function(filePath) {
            console.log("filePath:", filePath);
            var path = filePath.replace(localPath, "");
            sftp.fastPut(filePath, conf.ftpUploadPath + path, function(
              err,
              result
            ) {
              fileCount -= 1;
              if (fileCount === 0) {
                conn.end();
                // then(err, result);
              }
            });
          },
          function(dirPath, next) {
            console.log("dirPath:", dirPath);
            var path = dirPath.replace(localPath, "");
            sftp.mkdir(conf.ftpUploadPath + path, function(err, result) {
              next();
            });
          }
        );
      }
    });
  });
}
function Connect(server, then) {
  var conn = new Client();
  conn
    .on("ready", function() {
      then(conn);
    })
    .on("error", function(err) {
      //console.log("connect error!");
    })
    .on("end", function() {
      //console.log("connect end!");
    })
    .on("close", function(had_error) {
      //console.log("connect close");
    })
    .connect(server);
}

function walk(path, handleFile, handleDir) {
  fs.readdir(path, function(err, files) {
    if (err) {
      console.log("read dir error");
    } else {
      files.forEach(function(item) {
        var tmpPath = path + "/" + item;
        fs.stat(tmpPath, function(err1, stats) {
          if (err1) {
            console.log("stat error");
          } else {
            if (stats.isDirectory()) {
              handleDir(tmpPath, function() {
                walk(tmpPath, handleFile, handleDir);
              });
            } else {
              fileCount += 1;
              handleFile(tmpPath);
            }
          }
        });
      });
    }
  });
}
